package se.vgregion.excel.repository;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.util.Collection;

import org.springframework.transaction.annotation.Transactional;

import se.vgregion.dao.domain.patterns.repository.db.jpa.JpaRepository;
import se.vgregion.excel.types.CubeExcelFile;
import se.vgregion.excel.tools.ExcelDocReplacer;

/**
 * Operations to manipulate or access the excel material in the db.
 * 
 * @author claes.lundahl
 */
public class CubeExcelService {

    private JpaRepository<CubeExcelFile, Long, Long> excelRepository;

    public JpaRepository<CubeExcelFile, Long, Long> getExcelRepository() {
        return excelRepository;
    }

    public void setExcelRepository(JpaRepository<CubeExcelFile, Long, Long> excelRepository) {
        this.excelRepository = excelRepository;
    }

    @Transactional
    public Collection<CubeExcelFile> fetch() {
        return this.excelRepository.findAll();
    }

    /**
     * Finds a certain document and fills in information in its content that corresponds to that of the user
     * (userName).
     * 
     * @param id
     *            technical id of the document to find.
     * @param userName
     *            the name to fill in into the document.
     * @param baos
     *            the stream into wich to write the result.
     */
    @Transactional
    public void findStreamFromExcelCubeFile(Long id, String userName, OutputStream baos) {
        CubeExcelFile file = excelRepository.find(id);
        ByteArrayInputStream bais = new ByteArrayInputStream(file.getBytes());

        ExcelDocReplacer edr = new ExcelDocReplacer();
        edr.process(bais, baos, file.getUserNamePlaceHolder(), userName);
    }

    /**
     * Gets an stream with the modified document denoted by the id parameter provided.
     * 
     * @param id
     *            technical id of the document.
     * @param userName
     *            the user name write into the result.
     * @return the file (spread sheet-document).
     */
    @Transactional
    public OutputStream findStreamFromExcelCubeFile(Long id, String userName) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        findStreamFromExcelCubeFile(id, userName, baos);
        return baos;
    }

}
